package threads.futureTask;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class FutureTaskTest  {
    public static void main(String[] args) {
        FutureTask<String> futureTask = new FutureTask<String>(new Callable<String>() {
            @Override
            public String call()throws Exception  {
                while (true) {
                    if (Thread.currentThread().isInterrupted()) {
                        System.out.println("I have be canceled!!!!");
                        break;
                    }
//                    Thread.currentThread().sleep(1000);
                    System.out.println("I am running!");

                }
                return "SUCCESS";
            }
        });

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println(Thread.currentThread().getName()+" will get the futureTask's result!");
                    String result = futureTask.get();
                    System.out.println(Thread.currentThread().getName()+" had got the rusult of the futureTask : "+result);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        },"T1");
        t1.start();
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                futureTask.run();
            }
        });
        t2.start();

        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.currentThread().sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("I will cancel the process!");
                futureTask.cancel(true);
            }
        });
        t3.start();

    }
}
